import { EVENT, TYPES } from './constant/index';
import events from 'events';
import { io } from 'socket.io-client';
import Message from './message';

const EventEmitter = events.EventEmitter;

class IM extends EventEmitter {
  constructor() {
    super();
    this.EVENT = EVENT;
    this.TYPES = TYPES;
    this.userID = '';
    this.socket = io('ws://192.168.3.61:9000');
    this.listener();
  }

  /**
   * im 登录
   * @param {Object} param
   * @param {String} param.userID
   * @returns Promise
   */
  login({ userID }) {
    this.userID = userID;
    this.socket.emit('login', { userID: userID });
  }

  /**
   * im 登出
   * @returns Promise
   */
  logout() {
    this.socket.emit('logout', { userID: this.userID });
  }

  /**
   * 创建文本消息
   * @param {Object} options
   * @param {String} options.to
   * @param {String} options.conversationType
   * @param {Object} options.payload
   * @param {String} options.payload.text
   * @returns Message
   */
  createTextMessage(options) {
    options.from = this.userID;
    return new Message(options);
  }

  /**
   * 发送消息
   * @param {Message} message
   */
  sendMessage(message) {
    this.socket.send(message);
  }

  listener() {
    this.socket.on('connect', () => {
      this.emit(EVENT.SDK_READY);
      this.socket.on('message', (data) => {
        console.log('messaage: ', data);
        this.emit(EVENT.MESSAGE_RECEIVED, data);
      });
    });
  }
}

export default IM;
